import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

import { BASE_URL } from '../../config';

interface UserState {
  loading: boolean;
  error: string | null;
  token: string | null;
}

// 创建异步任务
export const signIn = createAsyncThunk(
  'user/signIn', // 命名空间
  async (parameter: { email: string; password: string }) => {
    const { data } = await axios.post(`${BASE_URL}/auth/login`, {
      email: parameter.email,
      password: parameter.password
    });
    return data.token;
  }
);
const initialState: UserState = {
  loading: false,
  error: null,
  token: null
};

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logOut: (state) => {
      state.token = null;
      state.error = null;
      state.loading = null;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(signIn.pending, (state) => {
        state.loading = true;
      })
      .addCase(signIn.fulfilled, (state, action) => {
        state.loading = false;
        state.token = action.payload;
      })
      .addCase(signIn.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as any;
      });
  }
});
